/**
 * 节点创建
 * @param nodeType 节点类型
 * @param property 节点属性
 * @returns { Element } 节点
 */
export function createNode(nodeType: keyof HTMLElementTagNameMap, property: Record<string, any>) {
  const newNode = document.createElement(nodeType)
  Object.keys(property).forEach((key) => {
    if (key.startsWith("on")) return newNode.addEventListener(key.slice(2).toLowerCase(), property[key])
    if (key in newNode) return (newNode[key] = property[key])
    newNode.setAttribute(key, property[key])
  })
  return newNode
}

/**
 * 生成 uuid
 * @returns { string } 唯一的uuid
 */
export function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === "x" ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

/**
 * 为对象中的属性为空的值设置默认值
 * @param { object } target 目标对象
 * @param { any } defaultValue 默认值
 * @returns { object } 新对象
 */
export function setDefaultValue(target: Record<string, any>, defaultValue = ""): Record<string, any> {
  return Object.keys(target).reduce((prev, key) => {
    prev[key] = target[key] || defaultValue
    return prev
  }, {})
}
